<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width="500"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改账号' : '新建账号'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      layout="horizontal"
      ref="form"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 5 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 19 }, sm: { span: 24 } }"
    >
      <a-form-item label="代理商:" name="agentId">
        <a-select :disabled="shouldDisableUpdate"
          placeholder="请选择代理商"
          v-model:value="form.agentId"
          allow-clear>
          <a-select-option v-for="item in agentList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="姓名:" name="realName">
        <a-input v-model:value="form.realName" placeholder="请输入姓名最多20个字" maxlength="20" allow-clear
                 autocomplete="off" />
      </a-form-item>
      <a-form-item label="手机号:" name="phone">
        <a-input v-model:value="form.phone" placeholder="请输入手机号最多11位" allow-clear autocomplete="off"
                 maxlength="11" />
      </a-form-item>
      <a-form-item label="账号:" name="account">
        <a-input v-model:value="form.account" placeholder="请输入账号最多20个字" maxlength="20" allow-clear
                 autocomplete="new-account" />
      </a-form-item>
      <a-form-item label="密码:" name="password" v-if="!isUpdate">
        <a-input :disabled="shouldDisableUpdate" type="password" v-model:value="form.password" placeholder="8-16位数字、字母或符号组合" maxlength="16" allow-clear
                 autocomplete="new-password" />
      </a-form-item>
      <!--          <a-form-item label="密码:" name="password">
                  <a-input v-model:value="form.password" placeholder="请输入密码" allow-clear autocomplete="off"
                           size="large" style="width: 60%" />
                </a-form-item>-->

      <a-form-item v-if="(user.roleId === '3' && !isUpdate) ||(user.roleId === '4' && !isUpdate) || (form.roleId !== '1339550467939639306' && isUpdate)" label="员工类型" name="roleId">
        <a-radio-group
          :disabled="shouldDisableRoleId"
          default-value="1780314237760671746" v-model:value="form.roleId" button-style="solid">
          <a-radio-button value="1780314237760671746">代理商员工</a-radio-button>
          <a-radio-button v-if="!(user.roleId === '4' && !isUpdate)" value="1780314166642053121">代理商经理</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="上级经理:" v-if="showDropdown && ((user.roleId === '3' || user.roleId === '4') || isUpdate)" name="leaderId">
      <a-select
          :disabled="shouldDisableLeaderId"
          placeholder="选择上级经理"
          v-model:value="form.leaderId"
          allow-clear>
          <a-select-option v-for="item in jlList" :key="item.userId" :value="item.userId">
            {{ item.realName }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { onMounted, ref } from 'vue';
import { AgentApi } from '@/api/AgentApi';
import { AgentAccountApi } from '@/api/AgentAccountApi';
import { DashboardApi } from '@/api/DashboardApi';

export default {
  name: 'AgentAccountEdit',
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  setup() {
    // 页面初次挂载时加载下拉数据
    onMounted(async () => {
      this.form.roleId = '1780314237760671746';// 默认员工
    });

    // 上级员工是否展示标识
    const showDropdown = ref(false);

    return {
      showDropdown
    };
  },
  data() {

    // 加载经理候选人下拉数据
    let jlList;
    return {
      // 用户信息
      user: {},
      // 代理商信息
      agentList:[],
      jlList,
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        agentId: [{ required: true, message: '请选择代理商', type: 'string', trigger: 'blur' }],
        roleId: [{ required: true, message: '请选择员工类型', type: 'string', trigger: 'change' }],
        leaderId: [{ required: true, message: '请选择上级经理', type: 'string', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入姓名', type: 'string', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', type: 'string', trigger: 'blur' }],
        account: [{ required: true, message: '请输入账号', type: 'string', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', type: 'string', trigger: 'blur' }]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      shouldDisableLeaderId: false,
      shouldDisableRoleId:false,
      shouldDisableUpdate: false,
    };
  },

  mounted() {
    this.fetchAgentList();
    this.getUser();
  },
  watch: {
    visible() {
      if (!this.data) {
        // 打开弹窗时清空表单
        this.form.realName = '';
        this.form.phone = '';
        this.form.account = '';
        this.form.password = '';

        this.form.roleId = '1780314237760671746';// 默认员工
      } else {
        // 当弹窗打开时，重置data的值
        this.form = Object.assign({}, this.data);
      }
      // 清空表单校验信息
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
      if(this.visible === true){
        this.fetchAgentList();
      }
    },

    async 'form.agentId'() {
      await this.fetchJlList();
    },

    // 监听 form.roleId 的变化
    'form.roleId'(newRoleId) {
      // 根据roleId的值来决定是否显示下拉框
      this.showDropdown = (newRoleId === '1780314237760671746'); // 假设选中员工时显示下拉框
    },
    data() {
      if (this.data) {
        // 编辑的时候适配组件数据类型
        this.form = Object.assign({}, this.data);
        this.isUpdate = true;

        // 如果是代理商经理
        if(this.user.roleId === '4'){
          this.form.agentId = this.user.agentId;
          //this.form.leaderId = this.user.userId;
          this.shouldDisableLeaderId = true;
          this.shouldDisableRoleId = true;
        }else{
          this.shouldDisableLeaderId = false;
          this.shouldDisableRoleId = false;
        }

        // 编辑的时候禁用修改项
        // this.shouldDisableLeaderId = true;
        // this.shouldDisableRoleId = true;
        this.shouldDisableUpdate = true;

      } else {
        this.shouldDisableUpdate = false;

        // 新增-清除表格内容
        this.form = {
          roleId: '1780314237760671746'// 默认员工
        };
        // 如果是代理商管理员
        if(this.user.roleId === '3'){
          this.form.agentId = this.user.agentId;
        }
        // 如果是代理商经理
        if (this.user.roleId === '4') {
          this.form.agentId = this.user.agentId;
          this.form.leaderId = this.user.userId;
          this.shouldDisableLeaderId = true;
        } else {
          this.shouldDisableLeaderId = false;
        }
        this.isUpdate = false;
      }
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    }
  },
  methods: {
    // 获取用户信息
    async getUser() {
      const res = await DashboardApi.getUser();
      this.user = res.data;
    },

    async fetchAgentList() {
      const res = await AgentApi.findList({});
      this.agentList = res.data;
    },

    // 联动加载经理人
    async fetchJlList() {
      const res = await AgentAccountApi.findManagers({ agentId: this.form.agentId, roleId: '1780314166642053121' });
      this.jlList = res.data;
    },
    /**
     * 保存和编辑
     */
    async save() {
      // 校验表单
      await this.$refs.form.validate();

      // 校验账号只能录入  数字、字母、符号
      const reg = /^[a-zA-Z0-9._-]*$/;
      if (this.form.account && !reg.test(this.form.account)) {
        this.$message.error('账号只能输入数字、字母和 . _ -');
        this.loading = false;
        return;
      }

      // 校验联系人电话格式是11位
      if (this.form.phone.length !== 11) {
        this.$message.error('请输入11位手机号');
        return;
      }

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        result = AgentAccountApi.edit(this.form);
      } else {
        // 校验密码是8-16位数字、字母或符号组合
        const simplePasswordRegex = /^[a-zA-Z0-9!@#$%^&*(),.?":{}|<>]{8,16}$/;
        if (this.form.password && !simplePasswordRegex.test(this.form.password)) {
          this.$message.error('密码必须为8-16位数字、字母或符号组合');
          this.loading = false;
          return;
        }
        // 校验一个字符串不能是纯数字
        const notPureNumberRegex = /^(?!\d+$).*$/;
        if (this.form.password && !notPureNumberRegex.test(this.form.password)) {
          this.$message.error('密码必须为8-16位数字、字母或符号组合(当前纯数字)');
          this.loading = false;
          return;
        }
        // 校验一个字符串不能是纯字母
        const notPureLetterRegex = /^(?!^[a-zA-Z]+$).*/;
        if (this.form.password && !notPureLetterRegex.test(this.form.password)) {
          this.$message.error('密码必须为8-16位数字、字母或符号组合（当前纯字母）');
          this.loading = false;
          return;
        }
        // 校验一个字符串不能是纯字母
        const notPureSymbolRegex = /^(?![!@#$%^&*(),.?":{}|<>]+$).*$/;
        if (this.form.password && !notPureSymbolRegex.test(this.form.password)) {
          this.$message.error('密码必须为8-16位数字、字母或符号组合（当前纯符号）');
          this.loading = false;
          return;
        }
        result = AgentAccountApi.add(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          this.$message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     * @param value true-显示，false-隐藏
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }

  }
};
</script>

<style scoped>
</style>
